package com.lyy.mybatis.sensitive.interceptor;


import cn.hutool.core.util.StrUtil;
import com.lyy.mybatis.sensitive.annotation.SensitiveField;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;

import java.lang.reflect.Field;

/**
 * @author lyy 2024/11/23
 */
public class SensitiveBaseInterceptor {

    public String getFieldStr(Field field, Object object) throws IllegalAccessException {
        Object val = field.get(object);
        if (val == null || StrUtil.isBlank(val.toString())) {
            return null;
        }
        return val.toString();
    }

    public static boolean isEncryptField(Field field) {
        return field.isAnnotationPresent(SensitiveField.class);
    }

    public static boolean isEncryptField(Field field, Object obj) throws IllegalAccessException {
        return isEncryptField(field) && field.get(obj) instanceof String;
    }

    public static boolean isInsertOrUpdate(MappedStatement mappedStatement) {
        SqlCommandType type = mappedStatement.getSqlCommandType();
        return SqlCommandType.UPDATE == type || SqlCommandType.INSERT == type;
    }

    public static boolean isSelect(MappedStatement mappedStatement) {
        SqlCommandType type = mappedStatement.getSqlCommandType();
        return SqlCommandType.SELECT == type;
    }

    public String getMapperClassPath(MappedStatement mappedStatement) {
        String classPath = mappedStatement.getId();
        return classPath.substring(0, classPath.lastIndexOf("."));
    }
}
